package middleWare

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method                   //方法
		c.Header("Access-Control-Allow-Origin", "*") //所有域名都可以访问（http://localhost：8080）
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT")                                                          //设置可以通过访问的方法（*）
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type") //指定消息头(*)
		c.Header("Access-Control-Allow-Credentials", "true")//访问资格
		//放行所有OPTIONS方法
		if method == "OPTIONS" {//判断请求方法是不是option
			c.AbortWithStatus(http.StatusNoContent)//是的话就请求成功
		}
		// 处理请求
		c.Next()
	}
}
